<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <!-- 头部警告区域 -->
      <el-alert title="注意：只允许为第三级分类设置相关参数！"
                type="warning"
                :closable="false"
                show-icon>
      </el-alert>

      <!-- 选择商品分类 -->
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类：</span>
          <el-cascader v-model="selectedCateKeys"
                       :options="cateList"
                       :props="cascaderProps"
                       @change="parentCateChanged"
                       clearable></el-cascader>
        </el-col>
      </el-row>

      <!-- tabs页签区域 -->
      <el-tabs v-model="activeName"
               @tab-click="handleTabClick">
        <!-- 动态参数 -->
        <el-tab-pane label="动态参数"
                     name="many">
          <el-button type="primary"
                     size="mini"
                     :disabled="isBtnDisabled"
                     @click="addParamsDialogVisible = true">添加参数</el-button>
          <!-- 动态参数表格 -->
          <el-table :data="manyTableData"
                    border
                    stripe>
            <!-- 动态参数展开按钮 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 循环渲染的tag标签 -->
                <el-tag closable
                        :key="i"
                        v-for="(item, i) in scope.row.attr_vals"
                        @close="deleteEltag(scope.row,i)">{{item}}</el-tag>
                <!-- 新建tag标签 -->
                <!-- 文本框 -->
                <el-input class="input-new-tag"
                          v-if="scope.row.inputVisible"
                          v-model="scope.row.inputValue"
                          ref="saveTagInput"
                          size="small"
                          @keyup.enter.native="handleInputConfirm(scope.row)"
                          @blur="handleInputConfirm(scope.row)">
                </el-input>
                <!-- 添加按钮 -->
                <el-button v-else
                           class="button-new-tag"
                           size="small"
                           @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"
                             label="#"></el-table-column>
            <el-table-column label="参数名称"
                             prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary"
                           icon="el-icon-edit"
                           size="mini"
                           @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                <el-button type="danger"
                           icon="el-icon-delete"
                           size="mini"
                           @click="removeParamsById(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 静态属性 -->
        <el-tab-pane label="静态属性"
                     name="only">
          <el-button type="primary"
                     size="mini"
                     :disabled="isBtnDisabled"
                     @click="addParamsDialogVisible = true">添加属性</el-button>
          <!-- 静态属性表格 -->
          <el-table :data="onlyTableData"
                    border
                    stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 循环渲染的tag标签 -->
                <el-tag closable
                        :key="i"
                        v-for="(item, i) in scope.row.attr_vals"
                        @close="deleteEltag(scope.row,i)">{{item}}</el-tag>
                <!-- 新建tag标签 -->
                <!-- 文本框 -->
                <el-input class="input-new-tag"
                          v-if="scope.row.inputVisible"
                          v-model="scope.row.inputValue"
                          ref="saveTagInput"
                          size="small"
                          @keyup.enter.native="handleInputConfirm(scope.row)"
                          @blur="handleInputConfirm(scope.row)">
                </el-input>
                <!-- 添加按钮 -->
                <el-button v-else
                           class="button-new-tag"
                           size="small"
                           @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"
                             label="#"></el-table-column>
            <el-table-column label="属性名称"
                             prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary"
                           icon="el-icon-edit"
                           size="mini"
                           @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                <el-button type="danger"
                           icon="el-icon-delete"
                           size="mini"
                           @click="removeParamsById(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加数据对话框 -->
    <el-dialog :title="'添加'+ titleText "
               :visible.sync="addParamsDialogVisible"
               width="50%"
               @close="addParamsDialogClosed">
      <!-- 内容主体区域 -->
      <!-- 表单区域 -->
      <el-form label-width="100px"
               :model="addParamsForm"
               :rules="addParamsFormRules"
               ref="addParamsFormRef"
               status-icon>

        <!-- 数据名称 -->
        <el-form-item :label="titleText "
                      prop="attr_name">
          <el-input v-model="addParamsForm.attr_name"></el-input>
        </el-form-item>

      </el-form>
      <!-- 局部区域 -->
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="addParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="addParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改数据对话框 -->
    <el-dialog :title="'修改'+ titleText "
               :visible.sync="editParamsDialogVisible"
               width="50%"
               @close="editParamsDialogClosed">
      <!-- 内容主体区域 -->
      <!-- 表单区域 -->
      <el-form label-width="100px"
               :model="editParamsForm"
               :rules="editParamsFormRules"
               ref="editParamsFormRef"
               status-icon>

        <!-- 数据名称 -->
        <el-form-item :label="titleText "
                      prop="attr_name">
          <el-input v-model="editParamsForm.attr_name"></el-input>
        </el-form-item>

      </el-form>
      <!-- 局部区域 -->
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="editParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 选中的父级分类id数组
      selectedCateKeys: [],
      // 商品分类数据
      cateList: [],
      // 级联选择器的配置对象
      cascaderProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover'
      },
      // 激活选中的页签
      activeName: 'many',
      // 根据name 【many，only】获取的参数
      manyTableData: [],
      onlyTableData: [],
      addParamsDialogVisible: false,
      // 添加数据的表单
      addParamsForm: {
        attr_name: ''
      },
      addParamsFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },

      // 修改对话框有关数据
      editParamsDialogVisible: false,
      // 修改数据的表单
      editParamsForm: {
        attr_name: ''
      },
      editParamsFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.getCateList()
  },
  methods: {
    // 获取商品分类
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error('获取商品分类失败！')
      this.cateList = res.data
      console.log(this.cateList)
    },
    //  级联选择器选择了三级分类时触发
    parentCateChanged () {
      console.log({ 三级分类id: this.selectedCateKeys })
      this.getParams()
    },
    // tab栏页签点击时候
    handleTabClick () {
      console.log({ 当前tab栏: this.activeName })
      this.getParams()
    },
    // 发送请求向后台获取  动态参数/静态属性
    async getParams () {
      // 如果选择id 的长度不为三  证明没有选择三级分类
      if (this.selectedCateKeys.length !== 3) {
        // 清空选中的数据即可
        this.selectedCateKeys = []
        this.manyTableData = []
        this.onlyTableData = []
        return
      }
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
        params: {
          sel: this.activeName
        }
      })
      if (res.meta.status !== 200) return this.$message.error('获取参数失败')
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : []
        item.inputVisible = false
        item.inputValue = ''
      })
      if (this.activeName === 'many') {
        this.manyTableData = res.data
        console.log(this.manyTableData)
      } else {
        this.onlyTableData = res.data
        console.log(this.onlyTableData)
      }
    },
    // 添加数据对话框关闭时
    addParamsDialogClosed () {
      this.$refs.addParamsFormRef.resetFields()
    },

    // 确认按钮添加参数
    addParams () {
      // 验证表单
      this.$refs.addParamsFormRef.validate(async valid => {
        if (!valid) return
        // 发送添加参数请求
        const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, {
          attr_name: this.addParamsForm.attr_name,
          attr_sel: this.activeName
        })
        console.log(res)
        // 判断状态码
        if (res.meta.status !== 201) return this.$message.error(`添加${this.titleText}失败！`)
        this.$message.success(`添加${this.titleText}成功！`)
        this.addParamsDialogVisible = false
        this.getParams()
      })
    },
    // 修改数据对话框关闭时
    editParamsDialogClosed () {
      this.$refs.editParamsFormRef.resetFields()
    },
    // 打开修改对话框
    async showEditDialog (id) {
      this.editParamsDialogVisible = true
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes/${id}`, { params: { attr_sel: this.activeName } })
      if (res.meta.status !== 200) return this.$message.error(`获取${this.titleText}失败！`)
      this.editParamsForm = res.data
      this.$message.success(`获取${this.titleText}成功！`)
    },

    // 点击修改按钮进行修改
    editParams () {
      this.$refs.editParamsFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.editParamsForm.attr_id}`, {
          attr_name: this.editParamsForm.attr_name,
          attr_sel: this.activeName
        })
        console.log(res)
        if (res.meta.status !== 200) return this.$message.error(`修改${this.titleText}失败！`)
        this.$message.success(`修改${this.titleText}成功！`)
        this.getParams()
        this.editParamsDialogVisible = false
      })
    },
    // 删除参数
    async removeParamsById (id) {
      console.log(id)
      const confirmResult = await this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // confirmResult  点击确认返回 confirm
      // confirmResult  点击取消返回 cancel
      if (confirmResult !== 'confirm') return this.$message.info('已取消删除')
      // 发送删除参数请求
      const { data: res } = await this.$http.delete(`categories/${this.cateId}/attributes/${id}`)
      if (res.meta.status !== 200) return this.$message.error(`删除${this.titleText}失败！`)
      this.$message.success(`删除${this.titleText}成功！`)
      this.getParams()
    },
    // 点击按钮展示输入框
    showInput (row) {
      console.log(row)
      row.inputVisible = true
      // 让文本框重新渲染后再自动获得焦点
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 添加标签
    async handleInputConfirm (row) {
      // 判断是否是合法字符串
      if (row.inputValue.trim().length === 0) {
        row.inputVisible = false
        row.inputValue = ''
      }
      // 不输入东西不发送请求
      if (row.inputValue) {
        row.attr_vals.push(row.inputValue.trim())
        row.inputValue = ''
        row.inputVisible = false

        this.saveAttrVals(row, '添加')
        // 发送请求同步后台数据
        // const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        //   attr_name: row.attr_name,
        //   attr_sel: this.activeName,
        //   attr_vals: row.attr_vals.join(',')
        // })
        // if (res.meta.status !== 200) this.$message.error(`添加${this.titleText}失败！`)
        // this.$message.success(`添加${this.titleText}成功！`)
      }
    },
    // 操作参数的描述值抽离出来单独函数
    async saveAttrVals (row, how) {
      // 发送请求同步后台数据
      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: this.activeName,
        attr_vals: row.attr_vals.join(',')
      })
      if (res.meta.status !== 200) this.$message.error(`${how}${this.titleText}失败！`)
      this.$message.success(`${how}${this.titleText}成功！`)
    },
    // 修改标签
    async deleteEltag (row, i) {
      row.attr_vals.splice(i, 1)
      this.saveAttrVals(row, '删除')
      // await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
      //   attr_name: row.attr_name,
      //   attr_sel: this.activeName,
      //   attr_vals: row.attr_vals.join(',')
      // })
      // if (res.meta.status !== 200) this.$message.error(`删除${this.titleText}失败！`)
      // this.$message.success(`删除${this.titleText}成功！`)
    }
  },
  computed: {
    // 计算属性来绑定按钮需要禁用返回 true
    isBtnDisabled () {
      if (this.selectedCateKeys.length !== 3) {
        return true
      }
      return false
    },
    // 获取父级分类的id
    cateId () {
      if (this.selectedCateKeys.length === 3) {
        return this.selectedCateKeys[2]
      }
      return null
    },
    // 动态计算属性
    titleText () {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    }
  }

}
</script>

<style lang="less" scoped>
.cat_opt {
  margin-top: 15px;
}

.el-tag {
  margin: 5px;
}

.button-new-tag {
  margin: 5px;
}

.input-new-tag {
  width: 120px;
}
</style>
